<template>
  <div class="right-search-box">
    <div class="key-person">
      <div class="key-person-label">关键人：</div>
      <je-input
        v-model:value="pageData.keyword"
        placeholder="搜索"
        autocomplete="false"
        class="left-search-box"
      >
        <template #prefix>
          <i class="fal fa-search" style="padding-right: 2px"></i>
        </template>
      </je-input>
    </div>
    <div class="key-date">
      <div class="key-date-label">送交日期：</div>
      <je-range-picker
        v-model:value="rangeDate"
        ge-picker
        :locale="locale"
        :placeholder="['开始日期', '结束日期']"
        :get-popup-container="popupContainer"
        @change="changeRangeDate"
      />
    </div>
  </div>
  <div class="right-content-box">
    <div v-show="notifyList.length > 0 && !loading" class="right-content-main-box">
      <div v-for="notifyItem in notifyList" :key="notifyItem" class="right-content-item">
        <div class="right-content-item-top">
          <div class="item-top-left">
            <div
              class="item-top-point"
              :class="{
                'item-point-read': notifyItem.USERMSG_YD == 1,
                'item-point-unread': notifyItem.USERMSG_YD == 0,
              }"
            ></div>
            <div
              class="item-top-name"
              @click="handleNotify(notifyItem)"
              v-html="notifyItem.USERMSG_BT"
            ></div>
          </div>
          <div
            class="item-top-right"
            v-text="
              formatTime(
                notifyItem.SY_CREATEUSERNAME,
                notifyItem.USERMSG_JSSJ,
                notifyItem.USERMSG_MSGTYPE_CODE,
                notifyItem.USERMSG_JSR_NAME,
              )
            "
          ></div>
        </div>
        <div class="right-content-item-bottom" v-html="notifyItem.USERMSG_NR"></div>
      </div>
    </div>
    <div v-if="notifyList.length > 0 && !loading" class="page-box">
      <je-pagebar
        :page-size="pageData.limit"
        :total-count="pageData.totalCount"
        @load="loadData"
      ></je-pagebar>
    </div>
    <div v-loading="loading"></div>
    <div v-show="notifyList.length == 0 && !loading" class="no-data-box">
      <img :src="noData" alt="" />
      <div class="no-data-explain">暂无数据～</div>
    </div>
  </div>
  <notify-modal ref="nodifyModalRef" :notify-item="curNotifyItem" />
</template>

<script>
  import { defineComponent, reactive, toRefs, onMounted, ref, watch } from 'vue';
  import { useMicroStore } from '@common/store/micro-store';
  import { DatePicker, Input } from '@jecloud/ui';
  import locale from 'ant-design-vue/lib/date-picker/locale/zh_CN';
  import JePagebar from '@/components/page-bar.vue';
  import NotifyModal from '@/views/board-home/components/notify-modal.vue';
  import { getCurrentUser, dateFormat } from '@jecloud/utils';
  import noData from '@/assets/no-data.png';
  import { GetLoadUserMsg, UpdateReadStatus } from '@/api';
  export default defineComponent({
    name: 'NotifyItem',
    components: {
      JeRangePicker: DatePicker.RangePicker,
      JeInput: Input,
      JePagebar,
      NotifyModal,
    },
    props: {
      readStatus: {
        type: String,
        default: () => '',
      },
      handleAllRead: {
        type: Boolean,
        default: () => false,
      },
      msgType: {
        type: String,
        default: () => '',
      },
    },
    emits: ['unreadCount'],
    setup(props, { emit }) {
      const microStore = useMicroStore();
      let loading = ref(false); //请求数据loading
      let searchTimeout = null; //关键人搜索
      const state = reactive({
        noData, //缺省图
        rangeDate: null, //自定义时间
        locale,
        nodifyModalRef: null, //信息详情弹窗
        pageData: {
          userId: getCurrentUser()?.id, //用户id
          deptId: getCurrentUser()?.organization.id, //部门id
          msgType: props.msgType, //通知消息分类
          readStatus: props.readStatus, // 消息已读状态 0未读 1已读
          startTime: '', //开始时间
          endTime: '', //结束时间
          keyword: '', //关键字
          tableCode: 'JE_SYS_USERMSG',
          page: 1, //页数
          limit: 30, //每页限制条数
          totalCount: 0, //总条数
        },
        notifyList: [], //通知列表
        curNotifyItem: {}, //当前消息
        updateFlag: true, //更新已读状态标注
      });
      const methods = {
        popupContainer(triggerNode) {
          return triggerNode.parentNode;
        },
        changeRangeDate() {
          //日期变化
          if (state.rangeDate) {
            state.pageData.startTime = dateFormat(state.rangeDate[0].toDate(), 'YYYY-MM-DD');
            state.pageData.endTime = dateFormat(state.rangeDate[1].toDate(), 'YYYY-MM-DD');
          } else {
            state.pageData.startTime = '';
            state.pageData.endTime = '';
          }
          methods.loadData();
        },
        formatTime(createName, createTime, notifyCode, acceptName) {
          //时间显示转化格式
          const curDate = new Date(createTime);
          const showDate = dateFormat(curDate, 'MM/DD HH:mm');
          if (notifyCode == 'RC') {
            //日程
            return `${acceptName}${showDate}`;
          }
          return `${createName}${showDate}`;
        },
        loadData(pageInfo) {
          //加载通知信息列表
          if (pageInfo) {
            state.pageData.page = pageInfo.page;
          }
          loading.value = true;
          GetLoadUserMsg(state.pageData).then((res) => {
            if (res.code == 1000 && res.success) {
              const resData = res.data;
              state.pageData.totalCount = resData.totalCount;
              state.pageData.page = resData.currentPage;
              state.notifyList = resData.rows;
              if (state.pageData.keyword) {
                state.notifyList.forEach((notifyItem) => {
                  //标题高亮
                  notifyItem.USERMSG_BT = notifyItem.USERMSG_BT.replaceAll(
                    state.pageData.keyword,
                    `<span class="hight-str">${state.pageData.keyword}</span>`,
                  );
                  //通知内容
                  notifyItem.USERMSG_NR = notifyItem.USERMSG_NR.replaceAll(
                    state.pageData.keyword,
                    `<span class="hight-str">${state.pageData.keyword}</span>`,
                  );
                });
              }
              //未读状态时，需要更新未读总数量
              emit('unreadCount', resData.noReadCount);
              setTimeout(() => {
                loading.value = false;
              }, 100);
            }
          });
        },
        updateUnReadNum(lodaDataFlag = false) {
          //更新未读通知数量
          GetLoadUserMsg(state.pageData).then((res) => {
            if (res.code == 1000 && res.success) {
              const resData = res.data;
              state.pageData.totalCount = resData.totalCount;
              state.pageData.page = resData.currentPage;
              if (lodaDataFlag) {
                //是否刷新列表数据
                state.notifyList = resData.rows;
              }
              //未读状态时，需要更新未读总数量
              emit('unreadCount', resData.noReadCount);
            }
          });
        },
        handleNotify(notifyItem) {
          //操作当前消息
          if (notifyItem.USERMSG_YD == 0) {
            //未读需要标识为已读
            if (state.updateFlag) {
              const param = {
                JE_SYS_USERMSG_ID: notifyItem.JE_SYS_USERMSG_ID,
              };
              state.updateFlag = false;
              UpdateReadStatus(param).then((res) => {
                if (res.code == 1000 && res.success) {
                  state.updateFlag = true;
                  state.curNotifyItem = notifyItem;
                  state.nodifyModalRef.notifyModalVisible = true;
                  if (props.readStatus === '0') {
                    //未读列表更新数据
                    state.notifyList = state.notifyList.filter((curItem) => {
                      return notifyItem.JE_SYS_USERMSG_ID != curItem.JE_SYS_USERMSG_ID;
                    });
                  }
                  if (props.readStatus === '') {
                    //全部列表更新数据
                    state.notifyList.forEach((item) => {
                      if (item.JE_SYS_USERMSG_ID == notifyItem.JE_SYS_USERMSG_ID) {
                        item.USERMSG_YD = '1';
                      }
                    });
                  }
                  methods.updateUnReadNum();
                } else {
                  state.updateFlag = true;
                }
              });
            }
          } else {
            state.curNotifyItem = notifyItem;
            state.nodifyModalRef.notifyModalVisible = true;
          }
        },
        socketMessage(message) {
          //websocket通知
          if (message.busType == 'MSG') {
            //推送通知类型与当前选中类型相同时，需要刷新当前列表数据
            const messageData = JSON.parse(message.content);
            if (state.pageData.msgType == messageData.code) {
              //动态添加数据
              methods.updateUnReadNum(true);
            } else {
              methods.updateUnReadNum();
            }
          }
        },
      };
      watch(
        () => state.pageData.keyword,
        (newVal, oldVal) => {
          if (newVal !== oldVal) {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(() => {
              state.pageData.page = 1;
              methods.loadData();
            }, 1000);
          }
        },
      );
      watch(
        //监听全部已读操作
        () => props.handleAllRead,
        (val) => {
          if (val && props.readStatus == 0) {
            methods.loadData();
          }
        },
      );
      watch(
        //监听消息类型变化
        () => props.msgType,
        (newVal, oldVal) => {
          if (newVal != oldVal) {
            state.pageData.msgType = newVal;
            methods.loadData();
          }
        },
      );
      //注册websocket监听事件
      microStore.on('websocket-message', (message) => {
        methods.socketMessage(message);
      });
      onMounted(() => {
        methods.loadData();
      });
      return {
        loading,
        ...toRefs(state),
        ...methods,
      };
    },
  });
</script>
<style>
  .right-search-box .ant-picker-input > input:focus,
  .right-search-box .ant-picker-input > input-focused {
    border-color: transparent;
    box-shadow: 0 0 0 0 transparent;
  }
  .right-search-box .ant-picker-input > input:placeholder-shown {
    text-overflow: inherit;
  }
</style>
<style scoped lang="less">
  .right-search-box {
    width: 100%;
    height: 40px;
    padding: 0 20px;
    box-sizing: border-box;
    border-top: 1px solid #ecedf0;
    border-bottom: 1px solid #ecedf0;
    border-right: 1px solid #ecedf0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .key-person {
      display: flex;
      align-items: center;
      .key-person-label {
        font-size: 14px;
        color: #3f3f3f;
      }
      .ant-input-affix-wrapper {
        width: 160px;
        border: 1px solid #f5f5f5;
        box-sizing: border-box;
      }
    }
    .key-date {
      display: flex;
      align-items: center;
      .key-date-label {
        font-size: 14px;
        color: #3f3f3f;
      }
      .ant-picker {
        width: 322px;
        border: 1px solid #f5f5f5;
        box-sizing: border-box;
      }
    }
  }
  .right-content-box {
    width: 100%;
    height: 500px;
    box-sizing: border-box;
    border-right: 1px solid #ecedf0;
    border-bottom: 1px solid #ecedf0;
    position: relative;
    .right-content-main-box {
      width: 100%;
      height: 460px;
      overflow-y: auto;
    }
    .right-content-item {
      width: calc(100% - 40px);
      height: 70px;
      box-sizing: border-box;
      padding: 14px 0;
      background-color: #ffffff;
      border-bottom: 1px solid #ecedf0;
      margin: 0 20px;
      overflow: hidden;
      .right-content-item-top {
        width: 100%;
        height: 20px;
        line-height: 20px;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .item-top-left {
          display: flex;
          align-items: center;
          .item-top-point {
            width: 6px;
            height: 6px;
            border-radius: 50%;
          }
          .item-point-read {
            background-color: #a9aba9;
          }
          .item-point-unread {
            background-color: #ff625c;
          }
          .item-top-name {
            height: 20px;
            line-height: 20px;
            font-size: 14px;
            color: #3f3f3f;
            padding-left: 10px;
          }
        }
        .item-top-right {
          height: 20px;
          line-height: 20px;
          font-size: 14px;
          color: #a9aba9;
        }
      }
      .right-content-item-bottom {
        width: 100%;
        font-size: 12px;
        color: #a9aba9;
        padding-left: 16px;
        margin-top: 8px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        span {
          color: #3265f5;
          text-decoration: underline;
          cursor: pointer;
        }
      }
    }
    .right-content-item:last-child {
      border-bottom: none;
    }
    .right-content-item:hover .right-content-item-top .item-top-name {
      color: @primary-color;
      cursor: pointer;
    }
  }
  .right-content-box::-webkit-scrollbar {
    width: 0;
    height: 0;
  }
  .page-box {
    width: 100%;
    height: 40px;
    padding: 7px 20px 0;
  }
  .no-data-box {
    width: 100%;
    padding-top: 140px;
    img {
      display: block;
      width: 319px;
      height: 194px;
      margin: 0 auto;
    }
    .no-data-explain {
      width: 100%;
      text-align: center;
      font-size: 14px;
      color: #a9aba9;
      padding-top: 20px;
    }
  }
</style>
